from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from crm import models
import os
import json
from crm_demo import settings
from common_libs.permissions import permission
from django.contrib.auth.decorators import login_required
# Create your views here.

@login_required
@permission.check_permission
def stu_my_classes(request):
    '''显示所有参加的班级'''
    return render(request, 'student/stu_my_classes.html')


@login_required
@permission.check_permission
def studyrecords(request,enrollment_id):
    '''显示学习记录'''
    enrollment_obj = models.Enrollment.objects.get(id=enrollment_id)
    return render(request, 'student/studyrecords.html',{'enrollment_obj': enrollment_obj})


@login_required
@permission.check_permission
def homework_detail(request, studyrecord_id):
    '''作业详情页'''
    studyrecord_obj = models.StudyRecord.objects.get(id=studyrecord_id)
    class_id = str(studyrecord_obj.course_record.from_class_id)
    course_id = str(studyrecord_obj.course_record_id)
    data_dir = os.path.join(settings.HOMEWORK_UPLOAD_DIR, class_id, course_id, studyrecord_id)
    if request.method == 'POST':
        res_dict = {'status': True, 'message': '', 'errors': ''}
        if request.is_ajax():
            if not os.path.exists(data_dir):
                os.makedirs(data_dir, exist_ok=True)
            if len(os.listdir(data_dir)):
                res_dict['status'] = False
                res_dict['errors'] = '已提交过作业，请先删除旧文件再提交'
            else:
                for k,file_obj in request.FILES.items():
                    f = open(os.path.join(data_dir,file_obj.name),'wb')
                    for chunk in file_obj.chunks():
                        f.write(chunk)
                    f.close()
            res_dict['message'] = get_homework_files(data_dir)
            return HttpResponse(json.dumps(res_dict))
        else:
            url = reverse('studyrecords',kwargs={'enrollment_id': studyrecord_obj.student_id})
            return redirect(url)

    if os.path.exists(data_dir):
        homework_list = get_homework_files(data_dir)
    else:
        homework_list = []
    res_dict = {'studyrecord_obj': studyrecord_obj,
                'homework_list':homework_list}
    return render(request, 'student/homework_detail.html',res_dict)


@login_required
@permission.check_permission
def delete_homework(request, studyrecord_id, filename):
    '''删除作业文件'''
    studyrecord_obj = models.StudyRecord.objects.get(id=studyrecord_id)
    class_id = str(studyrecord_obj.course_record.from_class_id)
    course_id = str(studyrecord_obj.course_record_id)
    data_dir = os.path.join(settings.HOMEWORK_UPLOAD_DIR, class_id, course_id, studyrecord_id)
    file_path = os.path.join(data_dir, filename)
    if os.path.exists(file_path):
        os.remove(file_path)
        return HttpResponse('ok')
    else:
        return HttpResponse('wrong')


def get_homework_files(data_dir):
    '''获取已上传的作业列表'''
    return os.listdir(data_dir)